from apis import api_routes
from flask import g, request, jsonify, abort
from security.decoration import certification
from typing import Union
from public.statistics import calculate_cpk


@api_routes.route("/calculate/cpk", methods=["POST"])
@certification(auth=True, role=None)
def func_calculate_cpk_post_api():
    """
    CPK计算，前端传递需要计算数组， 完成API开发
    http://127.0.0.1:8080/api/calculate/cpk
    Content-Type=application/json
    methods=["GET"]
    {
    "data"  array[json{"key": "xx", "values": [float, float, float, ....]}]   需要计算CPK 数据
    数据可是如： [{"key": "温度", "values": [22.3, 36, 33.4]}, {"key": "湿度", "values": [22.3, 36, 33.4]}]
    }
    :return:
        {'status': 200, 'data': resp}
    ---
    tags:
      - CPK计算
    """

    # data: list = [{"key": "温度", "values": [22.3, 36, 33.4]}, {"key": "湿度", "values": [22.3, 36, 33.4]}]

    request_json = request.get_json()
    data: Union[list, None] = request_json.get("data")
    if data is None:
        abort(code=400)
    if isinstance(data, list) is False:
        return jsonify({'status': 4000, "msg": "数据格式错误"})
    resp: list = []
    for index, itr in enumerate(data):
        if isinstance(itr, dict) is False:
            return jsonify({'status': 4001, "msg": "数据格式错误, 数组里面必须字典类型"})
        key: Union[str, None] = itr.get("key")
        values: Union[list, None] = itr.get("values")

        for itr_i, itr_d in enumerate(values):
            if isinstance(itr_d, str) is True:
                values[itr_i] = float(itr_d)
                
        if key is None or values is None:
            return jsonify({'status': 4002, "msg": "数据格式错误, 数组json 缺少key或者values"})
        if isinstance(values, list) is False:
            return jsonify({'status': 4003, "msg": "数据格式错误, 数组json values 格式必须数组格式"})
        resp.append({
            "key": key,
            "value": calculate_cpk(values, 2)
        })
    return jsonify({'status': 200, "data": resp})
